﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.AspNetCore.Http;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Extentions;
using TrainingReminderSystem.Model;
using TrainingReminderSystem.Dal;
using System.Threading.Tasks;

namespace TrainingReminderSystem.Bll
{
    /// <summary>
    /// 意见反馈 逻辑层
    /// </summary>
    public partial class SysFeedbackBll : PcLoginedBll
    {
        #region 验证和完善问题反馈

        protected override AjaxResult<dynamic> ValidatePartial<T, TDbContext>(T tModel, bool isAdd, AjaxResult<dynamic> r, TDbContext tDb)
        {
            var model = tModel as SysFeedback;
            var db = tDb as DbEntities;
            if (model == null || db == null) return base.ValidatePartial(tModel, isAdd, r, tDb);

            model.EnumRunProject = SysConfig.EnumRunProject;
            if (model.EnumRunProject == EnumRunProject.系统后台端)
            {
                model.SysEmployeeID = CurrentEmployee.SysEmployeeID;
            }

            if (model.EnumRunProject == EnumRunProject.微信客户端)
            {
                model.SysCustomerID = CustomerLoginedBll.CurrentCustomer?.SysCustomerID;
                model.SysCustomerOpenID = CustomerLoginedBll.CurrentOpenID?.ID;
            }

            return base.ValidatePartial(tModel, isAdd, r, tDb);
        }

        #endregion

        #region 新建处理记录

        public AjaxResult<dynamic> ValidateRecord(SysFeedbackRecord model, bool isAdd, DbEntities db)
        {
            var r = new AjaxResult<dynamic>();
            if (model == null)
            {
                r.Message = LanguageHelper.NoSubmitData;
                return r;
            }
            model.ExTrimProperty();
            r = ValidatePartial(model, isAdd, r, db);
            if (r.Success == false) return r;
            r.Success = false;

            if (string.IsNullOrEmpty(model.DealContent))
            {
                r.Message = LanguageHelper.RequireString1<SysFeedbackRecord>(nameof(SysFeedbackRecord.DealContent));
                return r;
            }
            model.FileUrl = Base64Helper.SaveFileFromBase64(model.FileUrl);
            model.DealImageUrl1 = Base64Helper.SaveFileFromBase64(model.DealImageUrl1);
            model.DealImageUrl2 = Base64Helper.SaveFileFromBase64(model.DealImageUrl2);
            model.DealImageUrl3 = Base64Helper.SaveFileFromBase64(model.DealImageUrl3);
            model.DealImageUrl4 = Base64Helper.SaveFileFromBase64(model.DealImageUrl4);
            model.DealImageUrl5 = Base64Helper.SaveFileFromBase64(model.DealImageUrl5);

            if (SysConfig.EnumRunProject == EnumRunProject.系统后台端)
            {
                model.SysEmployeeID = CurrentEmployee.SysEmployeeID;
            }
            if (SysConfig.EnumRunProject == EnumRunProject.微信客户端)
            {
                model.SysCustomerID = CustomerLoginedBll.CurrentCustomer?.SysCustomerID;
                model.SysCustomerOpenID = CustomerLoginedBll.CurrentOpenID?.ID;
            }

            if (isAdd)
            {
                if (SysConfig.EnumRunProject == EnumRunProject.系统后台端)
                {
                    model.SysStoreID = CurrentStore.SysStoreID;
                }
                if (SysConfig.EnumRunProject == EnumRunProject.微信客户端)
                {
                    model.SysStoreID = CustomerLoginedBll.CurrentStore.SysStoreID;
                }
                model.CreateDate = DateTime.Now;
            }

            r.Success = true;
            return r;
        }

        public async Task<AjaxResult<dynamic>> AddRecord(SysFeedbackRecord model)
        {
            using (var db = Db)
            {
                return await AddRecord(model, db);
            }
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="model">添加的对象,成功之后model对象的主键能得到对象</param>
        /// <param name="db"></param>
        /// <returns></returns>
        internal async Task<AjaxResult<dynamic>> AddRecord(SysFeedbackRecord model, DbEntities db)
        {
            var r = new AjaxResult<dynamic>() { Success = false };
            if (db == null) db = Db;
            var tempAr = ValidateRecord(model, true, db);
            if (tempAr.Success == false)
            {
                r.Message = tempAr.Message;
                r.Result = tempAr.Result;
                r.Total = tempAr.Total;
                return r;
            }
            var tran = db.Database.CurrentTransaction;
            bool hasTran = tran != null;
            if (hasTran == false) tran = await db.Database.BeginTransactionAsync();
            try
            {
                db.SysFeedbackRecord.Add(model);
                string error = AddLog(db, model, EnumLogType.新建);
                if (!string.IsNullOrEmpty(error))
                {
                    return AjaxResult<dynamic>.ErrorResult(error);
                }
                await db.SaveChangesAsync();
                //r = AddUpdateSuccessPartial(model, true, r, db);
                //if (r.Success == false)
                //{
                //    return r;
                //}
                //处理主表状态
                string sql = $"update {nameof(SysFeedback)} set {nameof(SysFeedback.EnumDealStatus)}={(int)model.EnumDealStatus} where {nameof(SysFeedback.SysFeedbackID)}={model.SysFeedbackID}";
                db.Database.ExExecuteSqlCommand(sql);

                await db.SaveChangesAsync();
                if (hasTran == false)
                {
                    await tran.CommitAsync();
                    await tran.DisposeAsync();
                    tran = null;
                }
                r.Success = true;
                r.Message = LanguageHelper.Success;
                r.Result = model;
                return r;
            }
            catch (Exception ex)
            {
                ex.ExLogError(GetCurrentOther());
                r.Total = (int)EnumTotal.异常;
                r.Success = false;
                r.Message = string.Format(LanguageHelper.Fail1, ex.ExMessageWithInner());
                return r;
            }
            finally
            {
                if (hasTran == false && tran != null)
                {
                    await tran.RollbackAsync();
                    await tran.DisposeAsync();
                    tran = null;
                }
            }
        }

        #endregion

        #region 处理记录列表

        private Expression<Func<SysFeedbackRecord, bool>> InitSearchDelegeteRecord(Expression<Func<SysFeedbackRecord, bool>> where, string key, string val, DbEntities db)
        {
            var r = InitSearchDelegetePartial(where, key, val, db);
            if (r != null) return r;
            return null;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <param name="form"></param>
        /// <param name="sortField"></param>
        /// <param name="asc"></param>
        /// <returns></returns>
        public async Task<AjaxResult<dynamic>> GetListRecord(int index, int size, IFormCollection form = null, string sortField = "", bool asc = false)
        {
            using (var db = Db)
            {
                Expression<Func<SysFeedbackRecord, bool>> where = InitSearch<SysFeedbackRecord, DbEntities>(form, InitSearchDelegeteRecord, db); //拼接查询条件方法
                IQueryable<SysFeedbackRecord> query = OrderByPartial(db.SysFeedbackRecord, sortField, asc, db);
                int counts;
                var tempIDList = query.ExGetListByPage(index, size, out counts, where).Select(m => m.ID);
                var r = new AjaxResult<dynamic>();
                r.Total = counts;
                IQueryable<SysFeedbackRecord> list = query.AsNoTracking().Where(m => tempIDList.Contains(m.ID));
                var tempList = list.Select(m => new
                {
                    ID = m.ID,
                    SysFeedbackID = m.SysFeedbackID,
                    //SysFeedback = new 
                    //{
                    //    SysFeedbackID = m.SysFeedback.SysFeedbackID,
                    //    EnumRunProject = m.SysFeedback.EnumRunProject,
                    //    EnumDealStatus = m.SysFeedback.EnumDealStatus
                    //},
                    SysStoreID = m.SysStoreID,
                    //SysStore = new
                    //{
                    //    SysStoreID = (int?)m.SysStore.SysStoreID,
                    //    EnumSysStoreType = (EnumSysStoreType?)m.SysStore.EnumSysStoreType,
                    //    SysStoreName = m.SysStore.SysStoreName,
                    //    PhoneNumber = DbFun.fn_replaceNum(m.SysStore.PhoneNumber, CanSeePhone),
                    //    EnumStatus = (EnumStatus?)m.SysStore.EnumStatus
                    //},
                    SysEmployeeID = m.SysEmployeeID,
                    SysEmployee = new
                    {
                        SysEmployeeID = (int?)m.SysEmployee.SysEmployeeID,
                        EnumQuitStatus = (EnumQuitStatus?)m.SysEmployee.EnumQuitStatus,
                        SysEmployeeName = m.SysEmployee.SysEmployeeName,
                        SysEmployeePhone = DbFun.fn_replaceNum(m.SysEmployee.SysEmployeePhone, CanSeePhone),
                        CanSeePhone = (bool?)m.SysEmployee.CanSeePhone
                    },
                    SysCustomerID = m.SysCustomerID,
                    SysCustomer = new
                    {
                        SysCustomerID = (int?)m.SysCustomer.SysCustomerID,
                        EnumSysCustomerType = (EnumSysCustomerType?)m.SysCustomer.EnumSysCustomerType,
                        SysCustomerName = m.SysCustomer.SysCustomerName,
                        Phone = DbFun.fn_replaceNum(m.SysCustomer.Phone, CanSeePhone),
                        EnumStatus = (EnumStatus?)m.SysCustomer.EnumStatus
                    },
                    //SysCustomerOpenID = m.SysCustomerOpenID,
                    SysCustomerOpenID = db.SysCustomerOpenID.Where(n => n.ID == m.SysCustomerOpenID).Select(n => new
                    {
                        n.OpenID,
                        n.nickname,
                        n.headimgurl,
                        n.CreateDate
                    }).FirstOrDefault(),

                    //SysCustomerOpenID = m.SysCustomerOpenID,
                    DealContent = m.DealContent,
                    FileUrl = m.FileUrl,
                    DealImageUrl1 = m.DealImageUrl1,
                    DealImageUrl2 = m.DealImageUrl2,
                    DealImageUrl3 = m.DealImageUrl3,
                    DealImageUrl4 = m.DealImageUrl4,
                    DealImageUrl5 = m.DealImageUrl5,
                    EnumDealStatus = m.EnumDealStatus,
                    CreateDate = m.CreateDate,
                    Remark = m.Remark
                });
                var resultList = await tempList.ToListAsync();
                //return GetListByPagePartial(resultList, r, db);

                r.Success = true;
                r.Result = resultList;
                return r;
            }
        }

        #endregion
    }
}
